<?php

/**
 * @author 陈韵
 * 聚水潭bc直邮
 */
namespace App\Service\OrderService\OrderRouteService;
use App\Service\Code\Normal;
use App\Model\PssModel\OrderSupplier;
use Service\AppService\IdService;
use App\Service\OrderService\BaseSupplierRouterService;
use App\Service\VendorClient\Shopjushuitan\ShopjushuitanApiClient;
use App\Model\CommodityModel\SupplierCommodity;
use App\Model\CommodityModel\SupplierCompany;
use App\Model\PssModel\OrderSupplierGoods;
use App\Service\VendorClient\ShopCaiNiao\ShopCaiNiaoBcApiClient;

class Shopjushuitan extends BaseSupplierRouterService
{
   /**
     * 创建订单
     * @param array $param
     * @return mixed
     */
    public function createOrder( $param = [] )
    {
        //生成供应商主单号
        $supplierGoodsInfo      = $param['supplierGoodsInfo'];
        $supplierCode           = $supplierGoodsInfo['supplierCode'];
        $apiBody                = $supplierGoodsInfo['apiBody'];
        $thirdPartyPlatformCode = $supplierGoodsInfo['thirdPartyPlatformCode'];
        //下单商品组
        $userGoodsList          = $supplierGoodsInfo['userGoodsList'];
        //下单商品
        $orderGoods = [];
        foreach ($userGoodsList as $item ) {
            $orderGoods = array_merge($orderGoods,$item);
            unset($item);
        }
        //通过apibody是否主动查询物流信息
        $isQueryExpress = isset($apiBody["is_query_express"])? (int)$apiBody["is_query_express"] : 1;
        //下游是否申报
        $isDelare = (
            (isset($param['order']['isOrderDeclare']) && $param['order']['isOrderDeclare'] == 1) ||
            (isset($param['order']['isPayDeclare']) && $param['order']['isPayDeclare'] == 1)
            ) ? true : false;
    
        //是否云仓商城
        $isShop = isset($param['order']['isSplitOrder']) && $param['order']['isSplitOrder'] == 1 ? true : false ;
        
        //防止订单号重复问题,下游已申报，则使用下游的订单号作为中台子单号
        if( $isDelare && !$isShop ) {
            $param['order']['supplier_dsn'] = (string)$param['order']['orderSn'];
        } else {
            $param['order']['supplier_dsn'] = (string)(IdService::instance()->getOtherID());
        }
        $param['order']['supplier_psn'] = OrderSupplier::instance()->getCreateOrderSn($supplierCode);
        $param['order']['supplier_csn'] = IdService::instance()->getOtherID();
        $param['order']['goods'] = $orderGoods;
        $param['order']['isQueryExpress'] = $isQueryExpress;//查询物流单
        $res = OrderSupplier::instance()->getSupplierCreateOrderData($param);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        
        $orderItems[] = $res['data'];
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'supplierCode' => $supplierCode,
            'orderItems' => $orderItems
        ]);
    }
    /**
     * 订单支付向菜鸟推
     * 
     * @param array $param
     * @return mixed
     */
    public function orderPay( $param = [] )
    {
        //如果有mode = derect没有则走正常模式，否则走余外直邮模式
        if(isset($param['apiBody']['mode']) &&  $param['apiBody']['mode'] == "derect"){
            return $this->callSdkApi(ShopjushuitanApiClient::class,$param['apiBody'])->createOrder($param);
        }
        //查询余外菜鸟配置
        $SupplierCode = $param['apiBody']['SupplierCode'];
        //查询菜鸟配置
        $supplierInfo = SupplierCompany::instance()->getSupplierListBySupplierCode($SupplierCode);
        if(empty($supplierInfo) or empty($supplierInfo["JsonBody"])){
            return Normal::returnCode(Normal::FAIL,"没有查询到菜鸟的配置，请核实！");
        }
        //查询菜鸟商品id
        $supplier_skuids = array_column($param['orderGoods'],'supplier_skuid');
        $supplier_skuids_map = SupplierCommodity::instance()->whereIn('ID',$supplier_skuids)->select(['ID','SupplierCommodityKey'])->get()->toArray();
        if(empty($supplier_skuids_map)){
            return Normal::returnCode(Normal::FAIL,"没有查询到菜鸟的备案id，请核实！");
        }
        $param['supplier_skuid_map'] = array_column($supplier_skuids_map,'SupplierCommodityKey','ID');
        //订单推给菜鸟
        return  $this->callSdkApi(ShopCaiNiaoBcApiClient::class,$supplierInfo["JsonBody"])->createOrder($param);
    }
    
    /**
     * 订单取消
     * @param array $param
     * @return mixed
     */ 
    public function orderCancel( $param = [] )
    {
        return Normal::returnCode(Normal::SUC,"处理完成");
    }
    
    /**
     * 订单售后
     * @param array $param
     * @return mixed
     */
    public function orderAfterSale($param = [])
    {
        return $this->callSdkApi(ShopjushuitanApiClient::class,$param['apiBody'])->cancelOrder($param);
    }
    
    
    /**
     * 商品列表查询接口
     * @param array $param
     */
    public function queryGoodsList( $param = [] )
    {
        $res = $this->callSdkApi(ShopjushuitanApiClient::class,$param['apiBody'])->{__FUNCTION__}($param['queryBody']);
        if( $res['code'] != Normal::SUC ) {
            return $res;
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'total'     => $res['data']['total'],
            'list'      => $res['data']['list'],
            'hasPage'   => $res['data']['has_next'] ?? false
        ]);
    }
    
    
    /**
     * 获取物流信息
     * @param array $param 
     */
    public function queryOrderExpress( $param = [] )
    {
        $queryBody = $param['queryBody'];
        $orderID   = $queryBody['orderID'];
        $apiBody   = $param['apiBody'];
        //查询订单商品信息
        $orderInfo = OrderSupplier::instance()->info(['id'=>$orderID,'company_id'=>$queryBody['supplierID']]);
        if( empty($orderInfo) ) {
            return Normal::returnCode(Normal::FAIL,"订单信息不存在，请核对！");
        }
        $param["supplierOrder"] = $orderInfo;
        $order_id = $orderInfo['id'];
        
       //查询余外菜鸟配置
       $supplierInfo = SupplierCompany::instance()->getSupplierListBySupplierCode($param["apiBody"]["SupplierCode"]);
       if(empty($supplierInfo) or empty($supplierInfo["JsonBody"])){
           return Normal::returnCode(Normal::FAIL,"没有查询到菜鸟的配置，请核实！");
       }

        //向菜鸟发起物流信息查询请求
        $res = $this->callSdkApi(ShopCaiNiaoBcApiClient::class,$supplierInfo["JsonBody"])->queryOrderExpress($param);
        if( $res['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,$res['msg']);
        }
        if( empty($res["data"]) ) {
            return Normal::returnCode(Normal::FAIL,"还未发货");
        }
        //业务逻辑处理
        $Result = current($res['data']["nodeList"]);
        $expressName  = $Result["partnerList"][0]['partnerName'];
        $expessNo     = $Result['mailNo'];
        
        $param["supplierOrder"]["express_sn"]=$expessNo;
        $param["supplierOrder"]["express_name"]=$expressName;
        
        //查询下单商品信息
        $orderGoods = OrderSupplierGoods::instance()
        ->select(OrderSupplierGoods::instance()->goods_fields)
        ->where('bid',$orderInfo["bid"])
        ->where('order_id',$orderInfo["id"])
        ->get()
        ->toArray();
        $param["orderGoods"] = $orderGoods;
        
        //查询菜鸟商品id
        $supplier_skuids = array_column($orderGoods,'supplier_skuid');
        $supplier_skuids_map = SupplierCommodity::instance()->whereIn('ID',$supplier_skuids)->select(['ID','SupplierCommodityKey'])->get()->toArray();
        if(empty($supplier_skuids_map)){
            return Normal::returnCode(Normal::FAIL,"没有查询到菜鸟的备案id，请核实！");
        }
        $param['supplier_skuid_map'] = array_column($supplier_skuids_map,'SupplierCommodityKey','ID');

        //向聚水潭推送订单
        $res = $this->callSdkApi(ShopjushuitanApiClient::class,$param['apiBody'])->createOrder($param);
        if( $res['code'] != Normal::SUC ) {
            return Normal::returnCode(Normal::FAIL,$res['msg']);
        }
        
        return  Normal::returnCode(Normal::SUC,"已发货",[
            'expressInfo' => [
                'express_name'  => $expressName,
                'express_sn'    => $expessNo,
            ]
        ]);
    }
    
}